package cn.codeforfun.util;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpSession;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Package cn.codeforfun.util
 * Project cloud-websocket
 * Author WangBin
 * Email bin.wang12@pactera.com
 * Created on 2017/8/14 0014 16:27
 * version 1.0.0
 */
@Component
public class UserService {
  private ConcurrentHashMap userMap = new ConcurrentHashMap();

  public String getCurrentUser() {
    HttpSession session = SpringUtil.getSession();
    Object      user    = session.getAttribute("user");
    if (user == null || StringUtils.isEmpty(user)) return null;
    return (String) user;
  }

  public boolean login(String name) {
    HttpSession session = SpringUtil.getSession();
    session.setAttribute("user", name);
    if (userMap.containsKey(name)) return false;
    userMap.put(name, name);
    return true;
  }

  public boolean logout() {
    HttpSession session = SpringUtil.getSession();
    String      name    = (String) session.getAttribute("user");
    session.invalidate();
    if (userMap.containsKey(name))
      userMap.remove(name);
    return true;
  }

}
